import React, { memo, useEffect, useState } from 'react';
import { history } from 'umi'

import { Spin, Button } from 'antd';

import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';

import CustomPopover from './component/CustomPopover';
import MyChartWrapper from './component/MyChartWrapper';
import EmptyWrapper from './component/EmptyWrapper';

import styles from './style.less'

const MyCharts = memo(({ organizationCode, loading, specialInfoList = [] }) => {
    const [chartList, setChartList] = useState([])
    const gotoEditChart = () => {
        const routeConfig = {
            pathname: '/finance/salary/statistics/perspective/edit',
            query: {
                organizationCode
            },
            state: {
                tabRoute: true,
                tabRefresh: true
            }
        }

        tabMessageUtil.memoFromTo(routeConfig.pathname, routeConfig.query);
        history.push(routeConfig);
    }

    const ChartTitle = () => (
        <div>
            <div>表示有员工在筛选月份内存在调岗</div>
            <div>的场景，薪资将按照该员工在调岗</div>
            <div>前后部门的在职天数分摊计算。</div>
        </div>
    )

    // 延迟一秒加载，每次加载3个图
    useEffect(() => {
        const timeoutFn = (data, len) => {
            setChartList([...data.slice(0, len)])
            if (data.length <= len) {
                return
            }

            setTimeout(() => {
                timeoutFn(data, len + 3)
            }, 1000)
        }

        timeoutFn(specialInfoList, 3)

        return () => {
            setChartList([])
        }
    }, [specialInfoList])

    return (
        <Spin spinning={loading}>
            <div className={styles.myCharts}>
                <div className={styles.chartHeader}>
                    <div className={styles.title}>
                        <span>我的图表</span>
                        <CustomPopover content={ <ChartTitle /> } title="员工小数说明：" />
                    </div>
                    <div className={styles.orgRight}>
                        <Button type="primary" onClick={gotoEditChart}>编辑图表</Button>
                    </div>
                </div>
                <div style={{ marginTop: -16 }}>
                    {
                        chartList?.map(item => item?.isEnable ?
                            <MyChartWrapper
                                title={item.globalName}
                                organizationCode={organizationCode}
                                key={item.globalType}
                                chartConfig={item} /> : null
                            )
                    }
                    {
                        (!specialInfoList || specialInfoList.length === 0) && !loading ?
                            <EmptyWrapper title="暂无图表，快去添加吧" handle={gotoEditChart} /> : null
                    }
                </div>
            </div>
        </Spin>
    )
})

export default MyCharts
